﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-09-08 13:50:58
 * 功能：进入游戏前的单个选择项
**************************************************************************************/

using Game.Framework;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

namespace Game.UI.ChoosePanel
{
    public class Item : MonoBehaviour
    {
        private Button m_EnterBtn, m_RefreshBtn;
        private Image m_Icon;
        private GameObject m_AnimObj, m_AdObj, m_RefreshIcObj, m_VideoIcObj;
        private GameDataModel.Level m_Level;
        private GameDataModel.AssetInfo m_Data;
        private int m_Idx;
        private ChoosePanelView m_RootView;

        private void Awake()
        {
            m_EnterBtn = transform.Find("EnterBtn").GetComponent<Button>();
            m_RefreshBtn = transform.Find("RefreshBtn").GetComponent<Button>();
            m_Icon = m_EnterBtn.transform.Find("Mask/Icon").GetComponent<Image>();
            m_AnimObj = m_EnterBtn.transform.Find("Anim").gameObject;
            m_AdObj = m_EnterBtn.transform.Find("Ad").gameObject;
            m_RefreshIcObj = m_RefreshBtn.transform.Find("RefreshIcon").gameObject;
            m_VideoIcObj = m_RefreshBtn.transform.Find("VideoIcon").gameObject;

            // 监听
            m_EnterBtn.onClick.AddListener(OnEnterBtnClick);
            m_RefreshBtn.onClick.AddListener(OnRefreshBtnClick);
        }

        private void OnEnterBtnClick()
        {
            if (m_AdObj.activeSelf)
            {
                // 先看广告再进入
                EventCenter.Instance.AddEventListen<EAdType, ETriggerAdType>(GameEventName.ON_CLOSE_AD, OnCloseAd);
                NativeInteraction.Instance.ShowRewardAd(ETriggerAdType.SelectIcon);
            }
            else
            {
                // 直接进入游戏
                m_Level.finalSelectIdx = m_Idx;
                UIUtility.DisplayPanel(GameLoadingPanel.GameLoadingPanelView.PANEL_KEY, "UI/GameLoadingPanel/Prefabs/GameLoadingPanel", data: m_Level);
                UIUtility.HidePanel(ChoosePanelView.PANEL_KEY);
            }
        }

        private void OnCloseAd(EAdType adType, ETriggerAdType triggerAdType)
        {
            if (adType == EAdType.RewardedVideo)
            {
                if (triggerAdType == ETriggerAdType.SelectIcon)
                {
                    m_Level.finalSelectIdx = m_Idx;
                    UIUtility.DisplayPanel(GameLoadingPanel.GameLoadingPanelView.PANEL_KEY, "UI/GameLoadingPanel/Prefabs/GameLoadingPanel", data: m_Level);
                    UIUtility.HidePanel(ChoosePanelView.PANEL_KEY);
                }
                else if (triggerAdType == ETriggerAdType.RefreshIcon)
                {
                    AssetCache.CacheSingleSmallImg(m_Level, m_Idx, succ =>
                    {
                        m_AnimObj.SetActive(false);
                        // 更新图片
                        if (succ) UpdateIcon();
                        m_RefreshBtn.interactable = true;
                    });
                }
                EventCenter.Instance.RemoveEventListen<EAdType, ETriggerAdType>(GameEventName.ON_CLOSE_AD, OnCloseAd);
            }
        }

        private void OnRefreshBtnClick()
        {
            m_RefreshBtn.interactable = false;
            m_AnimObj.SetActive(true);
            // 免费刷新
            if (!m_Level.cantFreeRefresh)
            {
                AssetCache.CacheSingleSmallImg(m_Level, m_Idx, succ =>
                {
                    m_AnimObj.SetActive(false);
                    if (succ)
                    {
                        m_Level.cantFreeRefresh = true;
                        m_RootView.FreeRefreshSucc(m_Idx);
                        RefreshBtnUpdate();
                        // 更新图片
                        UpdateIcon();
                    }
                    m_RefreshBtn.interactable = true;
                });
            }
            // 看广告刷新
            else
            {
                EventCenter.Instance.AddEventListen<EAdType, ETriggerAdType>(GameEventName.ON_CLOSE_AD, OnCloseAd);
                NativeInteraction.Instance.ShowRewardAd(ETriggerAdType.RefreshIcon);
            }
        }

        public void Init(GameDataModel.Level level, int idx, ChoosePanelView rootView)
        {
            m_RootView = rootView;
            m_Level = level;
            m_Data = level.assetsInfo == null ? null : level.assetsInfo[idx];
            m_Idx = idx;
            m_EnterBtn.interactable = m_Data != null || m_Data.rawUrl == null;
            m_RefreshBtn.interactable = m_Data != null;
            m_AnimObj.SetActive(m_Data == null || m_Data.rawUrl == null);
            RefreshBtnUpdate();
            UpdateIcon();

            if (m_Data != null && m_Data.rawUrl == null)
            {
                // 走到这里说明没用缓存成功，直接重新缓存缩略图
                var unusedCache = GameDataMgr.Instance.GetUnusedCache();
                if (unusedCache.Count > 0)
                {
                    var other = m_Level.GetCurAssetsInfo();
                    foreach (var item in unusedCache)
                    {
                        if (other.ContainsKey(item.Key)) continue;
                        var info = unusedCache.First().Value;
                        m_Data.id = info.id;
                        m_Data.type = info.type;
                        m_Data.rawUrl = info.rawUrl;
                        m_Data.smallUrl = info.smallUrl;
                        break;
                    }
                    if (m_Data.rawUrl != null)
                    {
                        m_AnimObj.SetActive(m_Data == null || m_Data.rawUrl == null);
                        UpdateIcon();
                    }
                    else
                    {
                        AssetCache.CacheSingleSmallImg(m_Level, m_Idx, succ =>
                        {
                            m_AnimObj.SetActive(m_Data == null || m_Data.rawUrl == null);
                            UpdateIcon();
                        });
                    }
                }
                else
                {
                    AssetCache.CacheSingleSmallImg(m_Level, m_Idx, succ =>
                    {
                        m_AnimObj.SetActive(m_Data == null || m_Data.rawUrl == null);
                        UpdateIcon();
                    });
                }
            }
        }

        private void UpdateIcon()
        {
            if (m_Data != null)
            {
                m_Icon.sprite = AssetCacheServer.Instance.GetSprite(m_Data.type, m_Data.id);
                IconResize();
            }
        }

        public void RefreshBtnUpdate()
        {
            m_RefreshIcObj.SetActive(m_Data == null || !m_Level.cantFreeRefresh);
            m_VideoIcObj.SetActive(m_Data != null && m_Level.cantFreeRefresh);
        }

        [ContextMenu("调整图标大小")]
        private void IconResize()
        {
            if (m_Icon.sprite == null) return;
            (float width, float height) finalSize = UIUtility.CalcSizeToFill(m_EnterBtn.GetComponent<RectTransform>(), m_Icon.sprite.texture);

            m_Icon.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, finalSize.width);
            m_Icon.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, finalSize.height);
        }

        public void Clear()
        {
            m_Icon.sprite = null;
        }

        public GameDataModel.AssetInfo Data => m_Data;
    }
}